package com.peanut.baby.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.http.HttpConfig;
import com.peanut.baby.model.BBSMoment;
import com.peanut.baby.model.LiveRoom;
import com.peanut.baby.model.QA;
import com.peanut.devlibrary.util.StringUtil;
import com.tencent.mars.xlog.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by anonymouslystudio on 2017/6/6.
 */

public class ShareUtil {
    private static final String TAG = ShareUtil.class.getSimpleName();

    private Context ctx;

    private static final String SHARE_TEXT = "花生备孕提供“远程指导+调理产品+门店服务”一体化的中医助孕优生一体化解决方案。";
    private static final String SHARE_URL = "http://sj.qq.com/myapp/detail.htm?apkName=com.peanut.baby";

    private static ShareUtil _instance;

    private ShareUtil() {
    }

    public static ShareUtil getInstance() {
        if (_instance == null) {
            _instance = new ShareUtil();
        }
        return _instance;
    }


    public void init(Context ctx){
        this.ctx = ctx;
    }

    public void share(String title,String text,String url,String platformName,String imgUrl,IShareCallback listener){
        if(platformName.equals(Wechat.NAME)){
            shareToWechat(title,text,url,imgUrl,listener);
        }else if(platformName.equals(WechatMoments.NAME)){
            shareToWechatMoment(title,text,url,imgUrl,listener);
        }else if(platformName.equals(QQ.NAME)){
            shareToQQ(title,text,url,imgUrl,listener);
        }else if(platformName.equals(SinaWeibo.NAME)){
            shareToWeibo(title,text,url,imgUrl,listener);
        }
    }



    public void shareQA(QA qa,String platformName,IShareCallback listener){
        String title = qa.description;
        String text = title;
        String imgUrl = qa.imageUrl;
        String userId = InitManager.getInstance().getUser() == null? "-1":InitManager.getInstance().getUserId();
        String url =  HttpConfig.QA_SHARE_URL + qa.id+"?userId="+userId;
        Log.d(TAG,"shareQA url "+url);
        if(platformName.equals(Wechat.NAME)){
            shareToWechat(title,text,url,imgUrl,listener);
        }else if(platformName.equals(WechatMoments.NAME)){
            shareToWechatMoment(title,text,url,imgUrl,listener);
        }else if(platformName.equals(QQ.NAME)){
            shareToQQ(title,text,url,imgUrl,listener);
        }else if(platformName.equals(SinaWeibo.NAME)){
            shareToWeibo(title,text,url,imgUrl,listener);
        }
    }
    public void shareMoment(BBSMoment m, String platformName, IShareCallback listener){
        Log.d(TAG,"shareMoment "+m.toString());
        String title = m.title;
        if(StringUtil.isNullOrEmpty(m.title)){
            title = StringUtil.getSimpleText(m.content);
        }

        String text = title;
        String imgUrl = getImageOne(m.imgUrl);


        String userId = InitManager.getInstance().getUser() == null? "-1":InitManager.getInstance().getUserId();
        String url =  HttpConfig.BBS_SHARE_URL + m.id+"?userId="+userId;
        Log.d(TAG,"shareMoment url "+url);
        if(platformName.equals(Wechat.NAME)){
            shareToWechat(title,text,url,imgUrl,listener);
        }else if(platformName.equals(WechatMoments.NAME)){
            shareToWechatMoment(title,text,url,imgUrl,listener);
        }else if(platformName.equals(QQ.NAME)){
            shareToQQ(title,text,url,imgUrl,listener);
        }else if(platformName.equals(SinaWeibo.NAME)){
            shareToWeibo(title,text,url,imgUrl,listener);
        }
    }

    String getImageOne(String imgOrg){
        try {
            return imgOrg.split(",")[0];
        } catch (Exception e) {
            return "";
        }
    };
    public void shareLive(LiveRoom room, String platformName, IShareCallback listener){
        String title = room.title;
        String text = title;
        String imgUrl = room.roomImageUrl;
        String userId = InitManager.getInstance().getUser() == null? "-1":InitManager.getInstance().getUserId();
        String url =  HttpConfig.LIVE_SHARE_URL + room.roomId+"?userId="+userId;
        Log.d(TAG,"shareLive url "+url);
        if(platformName.equals(Wechat.NAME)){
            shareToWechat(title,text,url,imgUrl,listener);
        }else if(platformName.equals(WechatMoments.NAME)){
            shareToWechatMoment(title,text,url,imgUrl,listener);
        }else if(platformName.equals(QQ.NAME)){
            shareToQQ(title,text,url,imgUrl,listener);
        }else if(platformName.equals(SinaWeibo.NAME)){
            shareToWeibo(title,text,url,imgUrl,listener);
        }
    }
    public void shareApp(String platformName,IShareCallback listener){
        String title = SHARE_TEXT;
        String text = SHARE_TEXT;
        String url = SHARE_URL;
        if(platformName.equals(Wechat.NAME)){
            shareToWechat(title,text,url,"",listener);
        }else if(platformName.equals(WechatMoments.NAME)){
            shareToWechatMoment(title,text,url,"",listener);
        }else if(platformName.equals(QQ.NAME)){
            shareToQQ(title,text,url,"",listener);
        }else if(platformName.equals(SinaWeibo.NAME)){
            shareToWeibo(title,text,url,"",listener);
        }
    }


    public void shareToQQ(String title,String text,String url,String imgUrl,final IShareCallback listener){
        Log.d(TAG,"shareToQQ");
        if(!isQQInstalled(ctx)){
            if(listener != null){
                listener.onShareFinished(false,QQ.NAME,"请安装或升级QQ客户端");
            }
            return;
        }
        Platform wx = ShareSDK.getPlatform(QQ.NAME);

        QQ.ShareParams wparams = new QQ.ShareParams();

        wparams.setText(text);
        wparams.setTitle(title);
        wparams.setShareType(Wechat.SHARE_WEBPAGE);
        wparams.setTitleUrl(url);
        if(!StringUtil.isNullOrEmpty(imgUrl)){
            wparams.setImageUrl(imgUrl);
        }else{
            wparams.setImagePath(getSharePicsPath());
        }

        wx.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.d(TAG,"onComplete");
                if(listener != null){
                    listener.onShareFinished(true,QQ.NAME,"");
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.d(TAG,"onError "+i+" "+throwable.toString());
                if(listener != null){
                    listener.onShareFinished(false,QQ.NAME,throwable.toString());
                }

            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.d(TAG,"onCancel "+i);
                if(listener != null){
                    listener.onShareFinished(false,QQ.NAME,"用户取消分享");
                }
            }
        });
        wx.share(wparams);
    }

    public void shareToWeibo(String title,String text,String url,String imgUrl,final IShareCallback listener){
        if(!isWeiboInstalled(ctx)){
            if(listener != null){
                listener.onShareFinished(false,SinaWeibo.NAME,"请安装或升级微博客户端");
            }
            return;
        }
        Platform wx = ShareSDK.getPlatform(SinaWeibo.NAME);

        SinaWeibo.ShareParams wparams = new SinaWeibo.ShareParams();

        wparams.setText(text + url);
//        wparams.setTitle(title);
//        wparams.setShareType(SinaWeibo.SHARE_WEBPAGE);

        if(!StringUtil.isNullOrEmpty(imgUrl)){
            wparams.setImageUrl(imgUrl);
        }else{
            wparams.setImagePath(getSharePicsPath());
        }

//        wparams.setUrl(url);
        wx.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.d(TAG,"onComplete");
                if(listener != null){
                    listener.onShareFinished(true,SinaWeibo.NAME,"");
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.d(TAG,"onError "+i+" "+throwable.toString());
                if(listener != null){
                    listener.onShareFinished(false,SinaWeibo.NAME,throwable.toString());
                }

            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.d(TAG,"onCancel "+i);
                if(listener != null){
                    listener.onShareFinished(false,SinaWeibo.NAME,"用户取消分享");
                }
            }
        });
        wx.share(wparams);
    }


    public void shareToWechat(String title,String text,String url,String imgUrl,final IShareCallback listener){
        if(!isWechatInstalled(ctx)){
            if(listener != null){
                listener.onShareFinished(false,Wechat.NAME,"请安装或升级微信客户端");
            }
            return;
        }
        Platform wx = ShareSDK.getPlatform(Wechat.NAME);

        Wechat.ShareParams wparams = new Wechat.ShareParams();

        wparams.setText(text);
        wparams.setTitle(title);
        wparams.setShareType(Wechat.SHARE_WEBPAGE);
        wparams.setUrl(url);
        if(!StringUtil.isNullOrEmpty(imgUrl)){
            wparams.setImageUrl(imgUrl);
        }else{
            wparams.setImagePath(getSharePicsPath());
        }
        wx.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.d(TAG,"onComplete");
                if(listener != null){
                    listener.onShareFinished(true,Wechat.NAME,"");
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.d(TAG,"onError "+i+" "+throwable.toString());
                if(listener != null){
                    listener.onShareFinished(false,Wechat.NAME,throwable.toString());
                }

            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.d(TAG,"onCancel "+i);
                if(listener != null){
                    listener.onShareFinished(false,Wechat.NAME,"用户取消分享");
                }
            }
        });
        wx.share(wparams);
    }

    /**
     *
     * @param title
     * @param text
     * @param url
     * @param listener
     */
    public void shareToWechatMoment(String title,String text,String url,String imgUrl,final IShareCallback listener){
        if(!isWechatInstalled(ctx)){
            if(listener != null){
                listener.onShareFinished(false,WechatMoments.NAME,"请安装或升级微信客户端");
            }
            return;
        }
        Log.d(TAG,"shareToWechatMoment3: "+title+" "+text+" "+url);
        Platform wx = ShareSDK.getPlatform(WechatMoments.NAME);

        WechatMoments.ShareParams wparams = new WechatMoments.ShareParams();

        wparams.setText(title);
        wparams.setTitle(text);
        wparams.setShareType(Platform.SHARE_WEBPAGE);
        if(!StringUtil.isNullOrEmpty(imgUrl)){
            wparams.setImageUrl(imgUrl);
        }else{
            wparams.setImagePath(getSharePicsPath());
        }
        wparams.setUrl(url);

        wx.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.d(TAG,"onComplete");
                if(listener != null){
                    listener.onShareFinished(true,WechatMoments.NAME,"");
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.d(TAG,"onError "+i+" "+throwable.toString());
                if(listener != null){
                    listener.onShareFinished(false,WechatMoments.NAME,throwable.toString());
                }

            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.d(TAG,"onCancel "+i);
                if(listener != null){
                    listener.onShareFinished(false,WechatMoments.NAME,"用户取消分享");
                }
            }
        });
        wx.share(wparams);
    }

    /**
     * 判断Instagram客户端是否安装
     *
     * @param act
     * @return
     */
    public boolean isWechatInstalled(Context act) {
        Log.d(TAG,"isWechatInstalled ctx == null? "+(ctx == null));
        String mmPkg = "com.tencent.mm";
        boolean isInstalled = false;
        List<PackageInfo> packageInfos = act.getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
        for (int i = 0; i < packageInfos.size(); i++) {
            PackageInfo temp = packageInfos.get(i);
            if (temp.packageName.equals(mmPkg)) {
                isInstalled = true;
                break;
            }

        }
        return isInstalled;
    }

    /**
     * 判断Instagram客户端是否安装
     *
     * @param act
     * @return
     */
    public boolean isWeiboInstalled(Context act) {
        String mmPkg = "com.sina.weibo";
        boolean isInstalled = false;
        List<PackageInfo> packageInfos = act.getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
        for (int i = 0; i < packageInfos.size(); i++) {
            PackageInfo temp = packageInfos.get(i);
            if (temp.packageName.equals(mmPkg)) {
                isInstalled = true;
                break;
            }

        }
        return isInstalled;
    }



    /**
     * 判断QQ客户端是否安装
     *
     * @param act
     * @return
     */
    public boolean isQQInstalled(Context act) {
        String qqPkg = "com.tencent.mobileqq";
        boolean isInstalled = false;
        List<PackageInfo> packageInfos = act.getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
        for (int i = 0; i < packageInfos.size(); i++) {
            PackageInfo temp = packageInfos.get(i);
            if (temp.packageName.equals(qqPkg)) {
                isInstalled = true;
                break;
            }
        }
        return isInstalled;
    }



    public String getSharePicsPath() {
        String name = "share.jpg";

        String path = InitManager.getInstance().getImageCacheDir() + File.separator + name;
        Log.d(TAG,"getSharePicsPath: "+path);
        ensureSharePictureExists(path);
        return path;
    }

    private void ensureSharePictureExists(String path) {
        Log.d(TAG,"ensureSharePictureExists  share_image jpg");
        File f = new File(path);
        if (!f.exists() || !f.isFile()) {
            //文件不存在 或者文件存在但不是文件格式
            if (f.exists()) {
                f.delete();
            }
            try {
                f.createNewFile();


                InputStream in = ctx.getResources().openRawResource(R.raw.share_image);

                FileOutputStream fos = new FileOutputStream(f);
                int len = -1;
                byte[] buffer = new byte[1024 * 100];
                while ((len = in.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                in.close();
                fos.close();
            } catch (Resources.NotFoundException e) {
                Log.d(TAG,"Resources.NotFoundException: "+e.toString());
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                Log.d(TAG,"FileNotFoundException: "+e.toString());
                e.printStackTrace();
            } catch (IOException e) {
                Log.d(TAG,"IOException: "+e.toString());
                e.printStackTrace();
            }
        }
    }


    public interface IShareCallback{
        void onShareFinished(boolean isSuccess, String platformName, String failReason);
    }
}
